# -*- coding:utf-8 -*-
# @Author : mistchan
# @Time : 2023/3/27 0027 21:00
# @File : sql_tools.py
# @Software: PyCharm
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtWidgets import QMessageBox


def dic_to_sql(cursor, dic):
    columns = ', '.join(dic.keys())
    placeholders = ', '.join('?' * len(dic))
    sql = 'INSERT INTO Media ({}) VALUES ({})'.format(columns, placeholders)
    cursor.execute(sql, tuple(dic.values()))


class SqlTools(object):
    def __init__(self, ui_obj):
        self.ui_obj = ui_obj
        self.con = con = QSqlDatabase.addDatabase('QSQLITE', 'my_connection')

        con.setDatabaseName('.\\DB\\data.db')

        if not con.open():
            QMessageBox.critical(ui_obj, "错误", "数据库未打开")
            return
        self.query = QSqlQuery(self.con)

    def do_sql(self, sql):
        self.query.prepare(sql)

    def run(self):
        self.query.exec()
        self.con.close()
